//
//  WBNetworkManager.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/18.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit
import AFNetworking

/// 枚举-请求方法
///
/// - GET: GET
/// - POST: POST
enum XMHTTPMethod {
    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {
    
    /// 单例类
    static let shared: WBNetworkManager = {
        
        let instance = WBNetworkManager()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    ///访问令牌，登录除外
    lazy var userAccount = WBUserAccount()

    /// 用户登录标记
    var userLogon : Bool  {
        
        return userAccount.access_token != nil
    }
    
    /// 带token的请求
    func tokenRequest(Method:XMHTTPMethod = .GET, URLString: String,parameters: [String: AnyObject]?, completed:@escaping ((_ json: AnyObject?, _ isSuccess: Bool)->())) {
        
        //处理accessToken
        var params = parameters
        
        guard userAccount.access_token != nil
            
            else {
                
            // 发送通知，提示用户登录
            print("没有token！需要登录")
                
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
                
            completed(nil, false)
                
            return
        }
        
        if params == nil  {
            
            params = [String: AnyObject]()
        }
        
        params!["access_token"] = userAccount.access_token as AnyObject?
        
        request(Method: Method, URLString: URLString, parameters: params, completed: completed)
    }
   
    
    /// 封装网络请求方法
    ///
    /// - Parameters:
    ///   - Method: GET/POST, 默认是GET请求
    ///   - URLString: 请求地址
    ///   - parameters: 参数
    ///   - completed: 结束回调
    func request(Method:XMHTTPMethod = .GET, URLString: String,parameters: [String: AnyObject]?, completed:@escaping ((_ json: AnyObject?, _ isSuccess: Bool)->())) {
        
        /// 定义成功回调闭包
        let success = { (task: URLSessionDataTask,json: Any?)->() in
            
            completed(json as AnyObject?,true)
        }
        
        /// 定义失败回调闭包
        let failure = {(task: URLSessionDataTask?, error: Error)->() in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                // 发送通知，提示用户再次登录
                print("token过期了，需要登录")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "token过期需要登录")
            }
            
            completed(nil,false)
        }
        
        /// 通过请求方法,执行不同的请求
        // 如果是 GET 请求
        if Method == .GET { // GET
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        } else { // POST
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
